<?php

declare(strict_types=1);

namespace think\seecms;

use seecms\See;
use seecms\SeeException;
use think\exception\Handle;
use think\Response;
use Throwable;

class ExceptionHandle extends Handle
{
    public function render($request, Throwable $e): Response
    {
        if ($request->isAjax() || $e instanceof SeeException) {

            $line = $e->getLine();
            $first = ($line - 9 > 0) ? $line - 9 : 1;
            try {
                $contents = file($e->getFile()) ?: [];
                $source = [
                    'first' => $first,
                    'source' => array_slice($contents, $first - 1, 19),
                ];
            } catch (\Exception $e) {
                $source = [];
            }

            $response = See::view()->fetch('exception', [
                'class' => [
                    'namespace' => get_class($e),
                    'name' => class_basename($e)
                ],
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'filename' => pathinfo($e->getFile(), PATHINFO_BASENAME),
                'line' => $e->getLine(),
                'severity' => method_exists($e, 'getSeverity') ? $e->getSeverity() : '0',
                'source' => $source
            ]);

            return Response::create($response, 'html', 500);
        }

        return parent::render($request, $e);
    }
}